use actix_session::Session;
use actix_web::{error::ErrorInternalServerError, web, Responder, Result};

use crate::{database::DbPool, route::form::menu::MenuForm, service::class};

pub fn config_api_menu(cfg: &mut web::ServiceConfig) {
    cfg.route("/menus", web::get().to(get_menus));
}

async fn get_menus(pool: web::Data<DbPool>, session: Session) -> Result<impl Responder> {
    let menus = class::menu::get_all(pool)
        .await
        .map_err(ErrorInternalServerError)?;
    let avaiable_menus = if session.get::<String>("uid")?.is_none() {
        filter_menus(menus, 1)
    } else {
        menus
    };
    Ok(web::Json(avaiable_menus))
}

fn filter_menus(menus: Vec<MenuForm>, level: i32) -> Vec<MenuForm> {
    menus
        .into_iter()
        .filter(|menu| menu.visibility_level <= level)
        .collect()
}
